//
//  AppDelegate.m
//  YAYIDoctor
//
//  Created by hxp on 16/4/28.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "AppDelegate.h"
#import <AudioToolbox/AudioToolbox.h>
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaSSOHandler.h"
#import "VRLoginViewController.h"


@interface AppDelegate ()

@end

@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
//    [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
//    application.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置SVProgressHUD 的样式
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6]];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setMinimumSize:CGSizeMake(60, 0)];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    
    // 分享相关（暂时去掉分享）
    [UMSocialData setAppKey:VRShareAppKey];
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:VRWXAppID appSecret:VRWXAppSecret url:@"https://www.yayi365.cn"];
    //设置手机QQ 的AppId，Appkey，和分享URL，需要#import "UMSocialQQHandler.h"
    [UMSocialQQHandler setQQWithAppId:VRQQAppID appKey:VRQQAppSecret url:@"https://www.yayi365.cn"];
    //打开新浪微博的SSO开关，设置新浪微博回调地址，这里必须要和你在新浪微博后台设置的回调地址一致。需要 #import "UMSocialSinaSSOHandler.h"
    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:VRWeiboID
                                              secret:VRWeiboSecret
                                         RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];

    
    
    /**
     *  友盟数据统计
     */
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    UMConfigInstance.appKey = @"5757d6a1e0f55a1ee60029b9";
    UMConfigInstance.channelId = @"App Store";
    UMConfigInstance.eSType = E_UM_NORMAL;
    [MobClick setEncryptEnabled:YES];
    //[MobClick setBackgroundTaskEnabled:YES];
    [MobClick startWithConfigure:UMConfigInstance];
    
    
    // 获取显示flag
    int showFlag = 1;
    //设置URL路径
    NSString *urlStr = [API_ShowFlag stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:urlStr];
    
    //通过URL设置网络请求
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    
    NSError *error=nil;
    //获取服务器数据
    NSData *requestData= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    if (error) {
        NSLog(@"错误信息:%@", [error localizedDescription]);
    }else{
        
        // 当前版本
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  
        
        // 远程版本
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:requestData options:NSJSONReadingMutableLeaves error:nil];
        NSString *originVersion = dict[@"iosversion"][@"version"];

        if ([app_Version isEqualToString:originVersion]) {
            
            showFlag = [dict[@"iosversion"][@"struts"] intValue];
        }
        
        NSLog(@"返回结果:%@",dict);
    }
    
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    if (showFlag == 1) {
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[VRLoginViewController alloc] init]];
        self.window.rootViewController = nav;
        
    }else{
        
        self.window.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
        self.window.rootViewController = [[YAYITabBarController alloc] init];
    }
    [self.window makeKeyAndVisible];
    
    

    return YES;
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
    
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""]
                          stringByReplacingOccurrencesOfString:@">" withString:@""]
                         stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"deviceToken:%@",token);
    /// [[SPKitExample sharedInstance] exampleSetDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    /**
     *  
     userInfo:{
     aps : {
     alert : a28a0a1bc0924a548c029371beb99f46,
     sound : default
     },
     i : 128076416
     }
     */
    NSLog(@"userInfo:%@",userInfo);
    
    
    /// [[SPKitExample sharedInstance] exampleHandleRunningAPNSWithUserInfo:userInfo];
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        
        NSDictionary *aps = userInfo[@"aps"];
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.alertBody =  aps[@"alert"];
        notification.userInfo = userInfo;
        notification.soundName = UILocalNotificationDefaultSoundName;
        //notification.alertAction = @"打开";
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                     categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            // 通知重复提示的单位，可以是天、周、月
            notification.repeatInterval = NSCalendarUnitDay;
        }
//        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        AudioServicesPlaySystemSound(1007);
        notification.repeatInterval = kCFCalendarUnitSecond;
        notification.soundName = UILocalNotificationDefaultSoundName;
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma 即时通讯
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
//- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
//{
//    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)]) {
//        [[UIApplication sharedApplication] registerForRemoteNotifications];
//    }
//}

#endif
//-(void)requestDeviceToken
//{
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
//    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)])
//    {
//        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound) categories:nil];
//        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
//        
//    } else
//#endif
//    {
//        /// 去除warning
//#pragma clang diagnostic push
//#pragma clang diagnostic ignored "-Wdeprecated-declarations"
//        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
//         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
//#pragma clang diagnostic pop
//    }
//    
//}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    // Check the calling application Bundle ID

    NSLog(@"Calling Application Bundle ID: %@", sourceApplication);
    NSLog(@"URL scheme:%@", [url scheme]);
    NSLog(@"URL query: %@", [url query]);
    
    return YES;

}



static AFHTTPSessionManager *manager;
- (AFHTTPSessionManager *)sharedHTTPSession{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 10;
    });
    return manager;
}



@end
